import {
  Card,
  Breadcrumb,
  Form,
  Button,
  Radio,
  Input,
  Upload,
  Space,
  Select,
  message
} from 'antd'
import { PlusOutlined } from '@ant-design/icons'
import { Link, useSearchParams } from 'react-router-dom'
import './index.scss'

import ReactQuill from 'react-quill'
import 'react-quill/dist/quill.snow.css'
import { useEffect, useState } from 'react'
import { creatArticleAPI, getArticleById,updateArticleAPI } from '@/apis/article'
import { getUserInfo } from '@/utils'
import { useChannel } from '@/hooks/useChannel'

const { Option } = Select

const Publish = () => {
  //获取频道列表
  const { channelList } = useChannel()

  //提交表单
  const onFinish = (formValue) => {
    console.log(formValue)
    //1、按照接口处理收集到的表单数据
    const { artTitle, artContent, channelId } = formValue
    const { userId } = JSON.parse(getUserInfo())
    console.log(userId)
    const reqData = {
      artCreate: new Date(),
      artTitle,
      status: 1,
      artContent,
      //封面模式
      artType: imageType,
      //图片列表
      artImages: (imageList.map(item => {
          if(item.response){
            return (item.response.data.url)
          }else{
            return (item.url)
          }
        })).toString(),
      readCount: 1,
      commentCount: 0,
      likeCount: 0,
      channelId,
      userId
    }
    //2、调用接口提交(新增/更新)
    if (articleId) {
      const reqData1 = {artId:articleId,...reqData}
      console.log(reqData1,imageList,imageList.length)
      updateArticleAPI(reqData1)
      message.success('文章-更新-成功')
    }else{
      //校验封面类型imageType和实际的图片列表imageList数量是否相等
      if (imageList.length !== +imageType) return message.warning('封面类型和图片数量不匹配')
      console.log(reqData)
      creatArticleAPI(reqData)
      message.success('文章-发布-成功')
    }
  }

  //封面上传回调
  const [imageList, setImageList] = useState([])
  const onChange = (value) => {
    console.log('封面正在上传中', value)
    setImageList(value.fileList)
  }

  //切换图片封面类型
  const [imageType, setImageType] = useState(0)
  const onTypeChange = (e) => {
    console.log('切换了封面类型', e.target.value)
    setImageType(e.target.value)
  }

  //回填数据
  const [searchParams] = useSearchParams()
  const articleId = searchParams.get('id')
  console.log(articleId)
  //获取实例
  const [form] = Form.useForm()
  useEffect(() => {
    //1.通过artId获取数据
    async function getArticleDetail() {
      const res = await getArticleById(articleId)
      const data1= res.data
      const artType1 = data1.artType
      //因为要调用sqlit所以artImages应该给个初始值，不然会报（TypeError: Cannot read properties of undefined (reading ‘split‘)）
      const artImages = data1.artImages || ''
      const artImages1 = artImages.split(',')
      form.setFieldsValue({
        ...data1,
        //这里因为属性里面的name为artType和我接口传回来参数名一样，所以不需单独解构
        //type:res.data.artType
      })
      //这里封面类型和数据没有回填（因为数据结构不一样，处理如下）
      //回填设置封面类型
      setImageType(artType1)
      //回填显示图片(数据结构url:url)(记得在页面标签加fileList={imageList})
      setImageList(artImages1.map( url =>{
        return {url}
      }))
    }
    //只有有id的时候才能调用此函数回填
    if (articleId){
      getArticleDetail()
    }
    //2.调用实例方法，完成回填
  }, [articleId, form])

  return (
    <div className="publish">
      <Card
        title={
          <Breadcrumb items={[
            { title: <Link to={'/'}>首页</Link> },
            { title: `${articleId ? '编辑' : '发布'}文章`},
          ]}
          />
        }
      >
        <Form
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 16 }}
          initialValues={{ artType: 0 }}
          onFinish={onFinish}
          form={form}
        >
          <Form.Item
            label="标题"
            name="artTitle"
            rules={[{ required: true, message: '请输入文章标题' }]}
          >
            <Input placeholder="请输入文章标题" style={{ width: 400 }} />
          </Form.Item>
          <Form.Item
            label="频道"
            name="channelId"
            rules={[{ required: true, message: '请选择文章频道' }]}
          >
            <Select placeholder="请选择文章频道" style={{ width: 400 }}>
              {/* value属性用户选中之后会自动收集起来作为接口的提交字段*/}
              {channelList?.map(item => <Option key={item.channelsId} value={item.channelsId}>{item.channelsName}</Option>)}
            </Select>
          </Form.Item>
          <Form.Item label="封面">
            <Form.Item name="artType" onChange={onTypeChange}>
              <Radio.Group>
                <Radio value={1}>单图</Radio>
                <Radio value={3}>三图</Radio>
                <Radio value={0}>无图</Radio>
              </Radio.Group>
            </Form.Item>
            {imageType > 0 && <Upload
              name="image"
              listType="picture-card"
              showUploadList
              //这里请求走的代理3000转8080（tomcat的/img指向G:\picture）
              action={'http://localhost:9090/images/upload'}
              onChange={onChange}
              maxCount={imageType}
              fileList={imageList}
            >
              <div style={{ marginTop: 8 }}>
                <PlusOutlined />
              </div>
            </Upload>}
          </Form.Item>
          <Form.Item
            label="内容"
            name="artContent"
            rules={[{ required: true, message: '请输入文章内容' }]}
          >
            {/* 富文本编辑器 */}
            <ReactQuill
              className="publish-quill"
              theme="snow"
              placeholder="请输入文章内容"
            />
          </Form.Item>

          <Form.Item wrapperCol={{ offset: 4 }}>
            <Space>
              <Button size="large" type="primary" htmlType="submit">
                {articleId ? '更新' : '发布'}文章
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>
    </div>
  )
}

export default Publish